<?php

class CronjobsController extends AppController {

    var $name = 'Cronjobs';
    var $uses = array('User', 'Invoice', 'Order', 'Product', 'QadminSummary', 'Setting');
    var $components = array('Email');

    function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allowedActions = array('*');
    }

    /*     * ****************************************************************************************
      -------------------------------Q-admin summary page-------------------------------------------
      This cron jobs should run once in a month(last day of the month) and time should be 00:00:01
     * ***************************************************************************************** */

    function qadmin_summary() {
        $this->layout = false;
        $this->User->recursive = -1;
        $this->Order->recursive = -1;
        $this->Product->recursive = -1;
        $start_date = date("Y-m-d H:i:s", mktime(0, 0, 0, date("m") - 1, 1, date("Y")));
        $end_date = date("Y-m-d H:i:s", mktime(0, 0, 0, date("m"), 1, date("Y")) - 1);
        $qadmins = $this->User->find('list', array('conditions' => array('User.group_id' => 2, 'User.active' => 1)));
        $i = 0;
        foreach ($qadmins as $qadmin) {
            $this->data['QadminSummary'][$i]['period1'] = $start_date;
            $this->data['QadminSummary'][$i]['period2'] = $end_date;
            $this->data['QadminSummary'][$i]['user_id'] = $qadmin;
            $total_app_products = $this->Product->find("count", array("conditions" => array("Product.approved_id" => $qadmin, "Product.approved_date BETWEEN ? AND ?" => array($start_date, $end_date))));
            $this->data['QadminSummary'][$i]['products_approved'] = $total_app_products;
            $sell_products = $this->Product->find("list", array("conditions" => array("Product.approved_id" => $qadmin), "fields" => array("Product.id")));
            $total_sell_products = $this->Order->find("count", array("conditions" => array("Order.product_id" => $sell_products, "Order.payment_status" => "Complete", "Order.add_date BETWEEN ? AND ?" => array($start_date, $end_date))));
            $this->data['QadminSummary'][$i]['product_sold'] = $total_sell_products;
            $this->data['QadminSummary'][$i]['total'] = round($total_sell_products * 0.30, 2);
            $i++;
        }
        $this->QadminSummary->saveAll($this->data['QadminSummary']);
        $this->autoRender = false;
    }

    /*     * ****************************************************************************************
      -------------------------------Product Auto Re-list-------------------------------------------
      This cron jobs should run everyday at 00:00:00
     * ***************************************************************************************** */

    function product_auto_re_list() {
        $this->layout = false;
        $this->Product->recursive = -1;
        $exp_products = $this->Product->find("all", array("conditions" => array("Product.auto_re_list" => "Yes", "Product.products_expiredDate <= " => date("Y-m-d H:i:s")), "fields" => array("Product.id,Product.products_expiredDate")));
        if ($exp_products) {
            $i = 0;
            foreach ($exp_products as $exp_product) {
                $this->data['Product'][$i]['id'] = $exp_product['Product']['id'];
                $nextWeek = 7 * 24 * 60 * 60;
                $this->data['Product'][$i]['products_expiredDate'] = date("Y-m-d H:i:s", strtotime($exp_product['Product']['products_expiredDate']) + $nextWeek);
                $i++;
            }
            $this->Product->saveAll($this->data['Product']);
        }
        $this->autoRender = false;
    }

    /*     * ****************************************************************************************
      -------------------------------Awaiting Invoices-------------------------------------------
      This cron jobs should run once in a month(last day of the month) and time should be 00:00:01
     * ***************************************************************************************** */

    function awaiting_invoices($id = null) {
        $this->layout = false;
        $this->User->recursive = -1;
        $this->Product->recursive = -1;
        $this->Cart->recursive = 2;
        $this->Setting->recursive = -1;
        $settings = $this->Setting->findById('1');

        $conditions = array("User.group_id" => array("3", "4", "5", "6"));
        $fields = array("User.id");
        $selles = $this->User->find("all", array("fields" => $fields));
        $i = 0;

        foreach ($selles as $seller) {
            $start_date = date("Y-m-d H:i:s", mktime(0, 0, 0, date("m") - 1, 1, date("Y")));
            $end_date = date("Y-m-d H:i:s");
            $seller_products = $this->Product->find("list", array('conditions' => array("Product.user_id" => $seller['User']['id']), 'fields' => array('Product.id')));

            $this->Cart->Behaviors->attach('Containable');
            $this->Cart->contain('Product.user_id', 'Order.add_date');
            $carts = $this->Cart->find('all', array(
                'conditions' => array('Cart.product_id' => $seller_products, 'Order.add_date BETWEEN ? AND ?' => array($start_date, $end_date))
                    ));
            //pr($carts);	
            if ($carts) {
                $total_cost = 0;
                $orders = "";
                foreach ($carts as $cart) {

                    $total_cost+=(($cart['Cart']['product_cost'] * $cart['Cart']['quantity']) + $cart['Cart']['shipping_cost'] + $cart['Cart']['sales_tax']);
                    $all_orders = explode(",", $orders);
                    if (!in_array($cart['Cart']['order_id'], $all_orders)) {
                        if (!empty($orders))
                            $orders.="," . $cart['Cart']['order_id'];
                        else
                            $orders.=$cart['Cart']['order_id'];
                    }
                }
                $this->data['Invoice'][$i]['orders'] = $orders;
                $this->data['Invoice'][$i]['total_sale'] = $total_cost;
                if ($settings && $settings['Setting']['aa_fee'] > 0) {
                    if ($settings['Setting']['fee_type'] == "%")
                        $this->data['Invoice'][$i]['aa_fee'] = ($settings['Setting']['aa_fee'] * $total_cost) / 100;
                    else
                        $this->data['Invoice'][$i]['aa_fee'] = $settings['Setting']['aa_fee'];
                }else
                    $this->data['Invoice'][$i]['aa_fee'] = "0.00";
            }
            else {
                $this->data['Invoice'][$i]['total_sale'] = "0.00";
                $this->data['Invoice'][$i]['aa_fee'] = "0.00";
            }
            $this->data['Invoice'][$i]['user_id'] = $seller['User']['id'];
            $this->data['Invoice'][$i]['invoice_date'] = date("Y-m-d H:i:s");
            $this->data['Invoice'][$i]['invoice_due_date'] = date("Y-m-d H:i:s", strtotime("+ 2days"));
            $i++;
        }
        $this->Invoice->create();
        $this->Invoice->saveAll($this->data['Invoice']);
        $this->autoRender = false;
    }

    /*     * *************************************************************************************
      -------------------------------Overdue Invoices----------------------------------------
      This cron jobs should run once in a month(at the end of the 2nd day of the month)
      and time should be 00:00:01
     * ************************************************************************************** */

    function overdue_invoices($id = null) {
        $this->layout = false;
        $invoice_due_date = date("Y-m-d H:i:s");
        $conditions = array("Invoice.invoice_status" => "Invoices Awaiting Payment", "Invoice.invoice_due_date <" => $invoice_due_date);
        $fields = array("Invoice.id", "Invoice.invoice_date", "Invoice.invoice_due_date", "Invoice.invoice_status");
        $overdue_invoices = $this->Invoice->find("all", array("conditions" => $conditions, "fields" => $fields));
        $i = 0;
        foreach ($overdue_invoices as $overdue_invoice) {
            $this->data['Invoice'][$i]['id'] = $overdue_invoice['Invoice']['id'];
            $this->data['Invoice'][$i]['invoice_status'][$i] = "Overdue Invoices";
            $this->data['Invoice'][$i]['invoice_due_date'][$i] = date("Y-m-d H:i:s", strtotime($overdue_invoice['Invoice']['invoice_date']) + (7 * 60 * 60));
            $i++;
        }
        $this->Invoice->saveAll($this->data['Invoice']);

        $this->autoRender = false;
    }

    function email() {
        $this->layout = null;
        $this->autoRender = false;
        $options = array('mc_gross' => 128.00,
            'item_number1' => 37, 'tax' => 0.00, 'item_number2' => 0, 'payer_id' => 'KLDQD68F8ZKXU',
            'address_street' => '1 Main St', 'payment_date' => '06:07:12 Oct 05, 2011 PDT',
            'payment_status' => 'Completed', 'custom' => 34506, 'num_cart_items' => 2, 'mc_handling1' => 0.00, 'mc_handling2' => 0.00,
            'mc_shipping1' => 0.00, 'mc_shipping2' => 0.00,
            'txn_id' => '1WF64557WL011434D', 'payment_type' => 'instant',
            'item_name1' => 'Marc Jacobs Triple Stitch Leather Clutch Handbag White NWT ',
            'item_name2' => 'Shipping and Handling',
            'payment_fee' => 4.01, 'quantity1' => 1, 'quantity2' => 1, 'receiver_id' => 'UNGMC3FQK622Q',
            'txn_type' => 'cart', 'mc_gross_1' => 100.00, 'mc_currency' => 'USD', 'mc_gross_2' => 28.00,
            'residence_country' => 'US', 'test_ipn' => 1, 'transaction_subject' => 34502, 'payment_gross' => 128.00,
            'ipn_track_id' => 'pXLis87eR1cVZUagGj0Kcw');
        $cart_ids = explode("|", $options['custom']);
        foreach ($cart_ids as $cart_id) {
            $cart = $this->Cart->find("first", array("conditions" => array("Cart.id" => $cart_id)));
        }
        $userinfo = $this->User->find("first", array("conditions" => array("User.id" => $cart['Cart']['user_id'])));

        //$this->Email->to = $userinfo['User']['username'].' < '.$userinfo['User']['email'].' >';
        $this->Email->to = $userinfo['User']['first_name'] . ' ' . $userinfo['User']['last_name'] . ' < sahbajuddin@yahoo.com >';
        $this->Email->subject = 'Invoice';
        $this->Email->from = 'authenticavenue.com < noreply@authenticavenue.com >';
        $this->Email->template = 'order_invoice'; // note no '.ctp'						
        $this->Email->sendAs = 'html';
        $this->set('userinfo', $userinfo);
        $this->set('status', $status);
        $this->set('orders', $options);
        $this->set('order_date', $cart['Cart']['add_date']);
        if ($this->Email->send())
            echo"Gone";
        else
            echo"Bad luck";
    }

}

?>